from VOModel import calcVelocity_Obstacle_Model
from CPAModel import calcCPA
import json, copy


def read_file(filename): 
    content = {}
    with open(filename, 'r', encoding='utf-8') as f:
        content = json.load(f)
        f.close()
    return content

def write_file(filename, content):
    with open(filename, 'w', encoding='utf-8') as f:
        json.dump(content, f)
        f.close()
    print("write to file {} successfully.".format(filename))

def speed_transfer(speed_knot):
    return speed_knot * 0.5144

def handle_data():
    '''
    data = {
        "mmsi1": {"datalist": [{$ship_data_1}, {$ship_data_2}]},
        "mmsi2": {"datalist": [{$ship_data_1}, {$ship_data_2}]},
        ... ...
    }
    本船 ship1 : 字典格式, {'lon': 111, 'lat':31, 'head': 70, 'vMax': 30}
    来船 ship2 : 字典格式, {'lon': 111, 'lat':31, 'head': 70, 'speed': 10}
    '''
    file_path = "C:/Users/Bruce Lee/Documents/workspace/3D-Maritime-Viewer/static/bigtable4u.js"
    ferry_mmsi = "413812634"
    content = read_file(file_path)
    data = copy.deepcopy(content)
    ferry = data.get(ferry_mmsi)
    print("data length: ", len(data))
    data_length = len(ferry.get("datalist"))
    VO_list = []

    for i in range(data_length):
        current_ferry_data = ferry.get("datalist")[i]
        current_risk_ship_mmsi = ferry.get("datalist")[i].get("MAX_RISK_SHIP")
        current_risk_ship_data = data.get(current_risk_ship_mmsi).get("datalist")[i]
        temp_ferry = {
            "lon": current_ferry_data.get("LON"),
            "lat": current_ferry_data.get("LAT"),
            "head": current_ferry_data.get("HEAD"),
            "speed": current_ferry_data.get("SPEED"),
            "vMax": 30
        }
        temp_risk_ship = {
            "lon": current_risk_ship_data.get("LON"),
            "lat": current_risk_ship_data.get("LAT"),
            "head": current_risk_ship_data.get("THEADING"),
            "speed": current_risk_ship_data.get("SPEED")
        }
        (VO_points, _) = calcVelocity_Obstacle_Model(temp_ferry, temp_risk_ship)
        transfered_ferry_speed = speed_transfer(temp_ferry["speed"])
        transfered_ship_speed = speed_transfer(temp_risk_ship["speed"])
        DCPA, TCPA = calcCPA(temp_ferry["lon"], temp_ferry["lat"], temp_ferry["head"], transfered_ferry_speed,\
            temp_risk_ship["lon"], temp_risk_ship["lat"], temp_risk_ship["head"], transfered_ship_speed)
        content.get(ferry_mmsi).get("datalist")[i].update({"VO_points": VO_points, "DCPA": DCPA, "TCPA": TCPA})
        VO_list.append(VO_points)

    # write_file("./vo4u.js", VO_list)
    write_file("./bigtable4u.js", content)

if __name__ == "__main__":
    handle_data()